<?php
require_once 'CMS/Util.php';
require_once 'CMS/User.php';
require_once 'CMS/Mvc/BaseController.php';
require_once 'CMS/Mvc/BaseAdminController.php';
require_once 'CMS/AdminCommon.php';
define('DIR_IMAGES', $_SERVER['DOCUMENT_ROOT'].'/');
//Người tạo : Huỳnh Trọng Hiếu
//Module 	: file manager
//Chức năng	: file manager

class Admin_FilemanagerController extends BaseAdminController {
		
	public function init(){
		parent::init();
		$this->_helper->layout->disableLayout();
		$user = new User();
		$user->init();
		$user->check_login();
		//$user->permission();
	}
	
	public function indexAction() {
		$this->view->entry_folder = 'New Folder:';
		$this->view->entry_move = 'Move:';
		$this->view->entry_copy = 'Name:';
		$this->view->entry_rename = 'Name:';
		
		$this->view->button_folder = 'New Folder';
		$this->view->button_delete = 'Delete';
		$this->view->button_move = 'Move';
		$this->view->button_copy = 'Copy';
		$this->view->button_rename = 'Rename';
		$this->view->button_upload = 'Upload';
		$this->view->button_refresh = 'Refresh'; 
		
		$this->view->error_select = 'Warning: Please select a directory or file!';
		$this->view->error_directory = 'Warning: Please select a directory!';
		
		
		$this->view->directory = '/data/';
		
		if (isset($_GET['field'])) {
			$this->view->field = $_GET['field'];
		} else {
			$this->view->field = '';
		}	
	}	
	
	
	public function directoryAction() {	
		$json = array();
		
		if (isset($_POST['directory'])) {
			$directories = glob(rtrim(DIR_IMAGES . 'data/' . str_replace('../', '', $_POST['directory']), '/') . '/*', GLOB_ONLYDIR); 
			
			if ($directories) {
				$i = 0;
			
				foreach ($directories as $directory) {
					$json[$i]['data'] = basename($directory);
					$json[$i]['attributes']['directory'] = substr($directory, strlen(DIR_IMAGES . 'data/'));
					
					$children = glob(rtrim($directory, '/') . '/*', GLOB_ONLYDIR);
					
					if ($children)  {
						$json[$i]['children'] = ' ';
					}
					
					$i++;
				}
			}		
		}

		$this->_helper->json($json);	
	}
	
	public function filesAction() {
		$json = array();
			
		if (isset($_POST['directory']) && $_POST['directory']) {
			$directory = DIR_IMAGES . 'data/' . str_replace('../', '', $_POST['directory']);
		} else {
			$directory = DIR_IMAGES . 'data/';
		}
		
		$allowed = array(
			'.jpg',
			'.jpeg',
			'.png',
			'.gif'
		);
		
		$files = glob(rtrim($directory, '/') . '/*');
		
		foreach ($files as $file) {
			if (is_file($file)) {
				$ext = strrchr($file, '.');
			} else {
				$ext = '';
			}	
			
			if (in_array(strtolower($ext), $allowed)) {
				$size = filesize($file);
	
				$i = 0;
	
				$suffix = array(
					'B',
					'KB',
					'MB',
					'GB',
					'TB',
					'PB',
					'EB',
					'ZB',
					'YB'
				);
	
				while (($size / 1024) > 1) {
					$size = $size / 1024;
					$i++;
				}
					
				$json[] = array(
					'file'     => substr($file, strlen(DIR_IMAGES . 'data/')),
					'filename' => basename($file),
					'size'     => round(substr($size, 0, strpos($size, '.') + 4), 2) . $suffix[$i],
					'thumb'    => "/".substr($file, strlen(DIR_IMAGES))
				);
			}
		}
		
		$this->_helper->json($json);
	}	
	
	public function createAction() {
				
		$json = array();
		
		if (isset($_POST['directory'])) {
			if (isset($_POST['name']) || $_POST['name']) {
				$directory = rtrim(DIR_IMAGES . 'data/' . str_replace('../', '', $_POST['directory']), '/');							   
				
				if (!is_dir($directory)) {
					$json['error'] = 'Warning: Please select a directory!';
				}
				
				if (file_exists($directory . '/' . str_replace('../', '', $_POST['name']))) {
					$json['error'] = 'Warning: A file or directory with the same name already exists!';
				}
			} else {
				$json['error'] = 'Warning: Please enter a new name!';
			}
		} else {
			$json['error'] = 'Warning: Please select a directory!';
		}
		
		
		if (!isset($json['error'])) {	
			mkdir($directory . '/' . str_replace('../', '', $_POST['name']), 0777);
			
			$json['success'] = 'Success: Directory created!';
		}	
		
		$this->_helper->json($json);
	}
	
	public function deleteAction() {
		
		$json = array();
		
		if (isset($_POST['path'])) {
			$path = rtrim(DIR_IMAGES . 'data/' . str_replace('../', '', $_POST['path']), '/');
			 
			if (!file_exists($path)) {
				$json['error'] = 'Warning: Please select a directory or file!';
			}
			
			if ($path == rtrim(DIR_IMAGES . 'data/', '/')) {
				$json['error'] = 'Warning: You can not delete this directory!';
			}
		} else {
			$json['error'] = 'Warning: Please select a directory or file!';
		}
		
		
		if (!isset($json['error'])) {
			if (is_file($path)) {
				unlink($path);
			} elseif (is_dir($path)) {
				$this->recursiveDelete($path);
			}
			
			$json['success'] = 'Success: Your file or directory has been deleted!';
		}				
		
		$this->_helper->json($json);
	}

	protected function recursivedelete($directory) {
		if (is_dir($directory)) {
			$handle = opendir($directory);
		}
		
		if (!$handle) {
			return FALSE;
		}
		
		while (false !== ($file = readdir($handle))) {
			if ($file != '.' && $file != '..') {
				if (!is_dir($directory . '/' . $file)) {
					unlink($directory . '/' . $file);
				} else {
					$this->recursiveDelete($directory . '/' . $file);
				}
			}
		}
		
		closedir($handle);
		
		rmdir($directory);
		
		return TRUE;
	}

	public function moveAction() {
		
		$json = array();
		
		if (isset($_POST['from']) && isset($_POST['to'])) {
			$from = rtrim(DIR_IMAGES . 'data/' . str_replace('../', '', $_POST['from']), '/');
			
			if (!file_exists($from)) {
				$json['error'] = 'Warning: File or directory does not exist!';
			}
			
			if ($from == DIR_IMAGES . 'data') {
				$json['error'] = 'Warning: Can not alter your default directory!';
			}
			
			$to = rtrim(DIR_IMAGES . 'data/' . str_replace('../', '', $_POST['to']), '/');

			if (!file_exists($to)) {
				$json['error'] = 'Warning: Move to directory does not exists!';
			}	
			
			if (file_exists($to . '/' . basename($from))) {
				$json['error'] = 'Warning: A file or directory with the same name already exists!';
			}
		} else {
			$json['error'] = 'Warning: Please select a directory!';
		}
		
		
		if (!isset($json['error'])) {
			rename($from, $to . '/' . basename($from));
			
			$json['success'] = 'Success: Your file or directory has been moved!';
		}
		
		$this->_helper->json($json);
	}	
	
	public function copyAction() {
		$json = array();
		
		if (isset($_POST['path']) && isset($_POST['name'])) {
			if ((strlen(utf8_decode($_POST['name'])) < 3) || (strlen(utf8_decode($_POST['name'])) > 255)) {
				$json['error'] = 'Warning: Filename must be a between 3 and 255!';
			}
				
			$old_name = rtrim(DIR_IMAGES . 'data/' . str_replace('../', '', $_POST['path']), '/');
			
			if (!file_exists($old_name) || $old_name == DIR_IMAGES . 'data') {
				$json['error'] = 'Warning: Can not copy this file or directory!';
			}
			
			if (is_file($old_name)) {
				$ext = strrchr($old_name, '.');
			} else {
				$ext = '';
			}		
			
			$new_name = dirname($old_name) . '/' . str_replace('../', '', $_POST['name'] . $ext);
																			   
			if (file_exists($new_name)) {
				$json['error'] = 'Warning: A file or directory with the same name already exists!';
			}			
		} else {
			$json['error'] = 'Warning: Please select a directory or file!';
		}
		
		
		
		if (!isset($json['error'])) {
			if (is_file($old_name)) {
				copy($old_name, $new_name);
			} else {
				$this->recursiveCopy($old_name, $new_name);
			}
			
			$json['success'] = 'Success: Your file or directory has been copied!';
		}
		
		$this->_helper->json($json);
	}

	function recursivecopy($source, $destination) { 
		$directory = opendir($source); 	
		
		@mkdir($destination); 
		
		while (false !== ($file = readdir($directory))) {
			if (($file != '.') && ($file != '..')) { 
				if (is_dir($source . '/' . $file)) { 
					$this->recursiveCopy($source . '/' . $file, $destination . '/' . $file); 
				} else { 
					copy($source . '/' . $file, $destination . '/' . $file); 
				} 
			} 
		} 
		
		closedir($directory); 
	} 

	public function foldersAction() {
		echo $this->recursiveFolders(DIR_IMAGES . 'data/');
		$this->_helper->json();	
	}
	
	protected function recursivefolders($directory) {
		$output = '';
		
		$output .= '<option value="' . substr($directory, strlen(DIR_IMAGES . 'data/')) . '">' . substr($directory, strlen(DIR_IMAGES . 'data/')) . '</option>';
		
		$directories = glob(rtrim(str_replace('../', '', $directory), '/') . '/*', GLOB_ONLYDIR);
		
		foreach ($directories  as $directory) {
			$output .= $this->recursiveFolders($directory);
		}
		
		return $output;
	}
	
	public function renameAction() {
		
		$json = array();
		
		if (isset($_POST['path']) && isset($_POST['name'])) {
			if ((strlen(utf8_decode($_POST['name'])) < 3) || (strlen(utf8_decode($_POST['name'])) > 255)) {
				$json['error'] = 'Warning: Filename must be a between 3 and 255!';
			}
				
			$old_name = rtrim(DIR_IMAGES . 'data/' . str_replace('../', '', $_POST['path']), '/');
			
			if (!file_exists($old_name) || $old_name == DIR_IMAGES . 'data') {
				$json['error'] = 'Warning: Can not rename this directory!';
			}
			
			if (is_file($old_name)) {
				$ext = strrchr($old_name, '.');
			} else {
				$ext = '';
			}		
			
			$new_name = dirname($old_name) . '/' . str_replace('../', '', $_POST['name'] . $ext);
																			   
			if (file_exists($new_name)) {
				$json['error'] = 'Warning: A file or directory with the same name already exists!';
			}			
		}
		
		
		
		if (!isset($json['error'])) {
			rename($old_name, $new_name);
			
			$json['success'] = 'Success: Your file or directory has been renamed!';
		}
		
		$this->_helper->json($json);
	}
	
	public function uploadAction() {
		
		$json = array();
		
		if (isset($_POST['directory'])) {
			if (isset($_FILES['image']) && $_FILES['image']['tmp_name']) {
				if ((strlen(utf8_decode($_FILES['image']['name'])) < 3) || (strlen(utf8_decode($_FILES['image']['name'])) > 255)) {
					$json['error'] = 'Warning: Filename must be a between 3 and 255!';
				}
					
				$directory = rtrim(DIR_IMAGES . 'data/' . str_replace('../', '', $_POST['directory']), '/');
				
				if (!is_dir($directory)) {
					$json['error'] = 'Warning: Please select a directory!';
				}
				
				if ($_FILES['image']['size'] > 300000) {
					$json['error'] = 'Warning: File to big please keep below 300kb and no more than 1000px height or width!';
				}
				
				$allowed = array(
					'image/jpeg',
					'image/pjpeg',
					'image/png',
					'image/x-png',
					'image/gif',
					'application/x-shockwave-flash'
				);
						
				if (!in_array($_FILES['image']['type'], $allowed)) {
					$json['error'] = 'Warning: Incorrect file type!';
				}
				
				$allowed = array(
					'.jpg',
					'.jpeg',
					'.gif',
					'.png',
					'.flv'
				);
						
				if (!in_array(strtolower(strrchr($_FILES['image']['name'], '.')), $allowed)) {
					$json['error'] = 'Warning: Incorrect file type!';
				}

				
				if ($_FILES['image']['error'] != UPLOAD_ERR_OK) {
					$json['error'] = 'error_upload_' . $_FILES['image']['error'];
				}			
			} else {
				$json['error'] = 'Warning: Please select a file!';
			}
		} else {
			$json['error'] = 'Warning: Please select a directory!';
		}
		
		
		
		if (!isset($json['error'])) {	
			if (@move_uploaded_file($_FILES['image']['tmp_name'], $directory . '/' . basename($_FILES['image']['name']))) {		
				$json['success'] = 'Success: Your file has been uploaded!';
			} else {
				$json['error'] = 'Warning: File could not be uploaded for an unknown reason!';
			}
		}
		
		$this->_helper->json($json);
	}
}